package com.sgolub.commanndsonline.jobs;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.sgolub.commanndsonline.dao.entity.AdvertisingRegistryDAO;
import com.sgolub.commanndsonline.domain.entity.OperationItem;
import com.sgolub.commanndsonline.service.entity.AdvertisingRegistryService;
import com.sgolub.commanndsonline.service.entity.OperationItemService;
import com.sgolub.commanndsonline.service.entity.OperationItemServiceImpl;
import com.sgolub.commanndsonline.ws.dao.AdvertisingRegistryItemDAO;
import com.sgolub.commanndsonline.ws.dao.AdvertisingRegistryOperationDAO;
import com.sgolub.commanndsonline.ws.entity.AdvertisingRegistryItem;
import com.sgolub.commanndsonline.ws.entity.AdvertisingRegistryOperation;
import com.sgolub.commanndsonline.ws.entity.DomParserPeriod;
import com.sgolub.commanndsonline.ws.entity.Period;
import com.sgolub.commanndsonline.ws.service.AdvertisingRegistryOperationService;

@Component("operationWorker")
public class OperationWorkerImplAsync implements OperationWorker {

	protected static Logger logger = Logger.getLogger("service");
	
	@Autowired
	private AdvertisingRegistryOperationService srcService;
	
	@Autowired
	private AdvertisingRegistryService  advertisingRegistryService;
	
	@Autowired
	private OperationItemService operationItemService;  
	
	@Async
	public void work() {
		  String threadName = Thread.currentThread().getName();
		  logger.debug("   " + threadName + " has began working.");
		         logger.debug("working...");
		         System.out.println("START * OperationWorker *" + new Date().toLocaleString());
		         syncronizeOperations();
		         System.out.println("STOP * OperationWorker *" + new Date().toLocaleString());		            
         logger.debug("   " + threadName + " has completed work.");
	}
	

	
	public void syncronizeOperations(){
		logger.debug("START * SYNC *" + new Date().toLocaleString());
		// Get unsynchronized Operation Items
		// If list is empty then return 
		List<AdvertisingRegistryOperation> srcList  = srcService.listActive();
		
		logger.debug("START * SYNC SIZE = *" + srcList.size());
		if (srcList.size() == 0){
			System.out.println("END * SYNC * NOTHING TO SYNCHRONIZE");
			return;
		}
		
		 
		// Iterate
		// Check
	    Iterator<AdvertisingRegistryOperation> itrSrc = srcList.iterator();
	      while(itrSrc.hasNext()) {
	    	 AdvertisingRegistryOperation elementSrc = itrSrc.next();
	    	 
	    	 
	    	 //Clear target OperationItem elements
	    	 Integer currentTargetId =  
	    			 advertisingRegistryService.getItemByInventarNr(elementSrc.getInventarNr()).getId();
	    	 
	    	 List<OperationItem> trgList  = new ArrayList<OperationItem>();
	    	 trgList = operationItemService.listByAdvertisingRegistryId(currentTargetId);
	    	 
	    	 Iterator<OperationItem> itrTrg = trgList.iterator();
	    	 while(itrTrg.hasNext()) {
	    		 OperationItem elementTrg = itrTrg.next();
	    		 operationItemService.remove(elementTrg.getId());
	    	 }
	    	 
	    	 //Item execution
	    	 logger.debug("Periods SIZE :" + elementSrc.getOccupationPeriods().length());
	    	 System.out.println(elementSrc.getOccupationPeriods());
	    	 
	    	 List<Period> periodsList = 
	    	 DomParserPeriod.getPeriodsFromXMLString(elementSrc.getOccupationPeriods());
	    	 
	    	 Iterator<Period> itrPeriod = periodsList.iterator();
	    	 while(itrPeriod.hasNext()) {
	    		 
	    		 Period elementTrg = itrPeriod.next();
	    		 
	    		 if(elementTrg.getStartDate() != null || elementTrg.getEndDate() != null){
	    			OperationItem opit = new OperationItem();
	    			opit.setInventarNr(elementSrc.getInventarNr());
	    			
	    			opit.setFkAdvertisingRegistryId(currentTargetId);
	    			
	    			opit.setBeginDate(elementTrg.getStartDate());
	    			opit.setEndDate(elementTrg.getEndDate());
	    			
	    			 logger.debug("elementTrg.getStatus() = " + elementTrg.getStatus() );
	    			 
	    			
	    			if (elementTrg.getStatus().equals("ПроданоПоДоговору")){
	    				opit.setReservationType(2);
	    			} else {
	    				if (elementTrg.getStatus().equals("Зарезервировано")){
	    				opit.setReservationType(1);
	    				} else {
	    				opit.setReservationType(0); 
	    				}	    				
	    			}
	    			operationItemService.add(opit);
	    		 }
	    	 }
	    	 elementSrc.setOperationExecutedStatus(1);
	    	 srcService.update(elementSrc);
	      }
		
	      logger.debug("END * SYNC *" + new Date().toLocaleString());
	      return;
		
	}

}
